package com.rt.tmpt.security.config;

import com.rt.tmpt.security.ImageCodeValidateFilter;
import com.rt.tmpt.security.MyAccessDecisionManager;
import com.rt.tmpt.security.MyFilterInvocationSecurityMetadataSource;
import com.rt.tmpt.security.handler.*;
import com.rt.tmpt.security.handler.MyAuthenticationEntryPoint;
import com.rt.tmpt.security.handler.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;


/**
 * @Author: wuxiaoyong
 * @Date: 2020/01/28
 * @Description: spring-security权限管理的核心配置
 **/
//@Configuration
//@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true) //全局
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //实现了UserDetailsService接口
    @Autowired
    private UserDetailsService myUserDetailService;

    //登录成功处理逻辑
    @Autowired
    private MyAuthenticationSuccessHandler authenticationSuccessHandler;

    //登录失败处理逻辑
    @Autowired
    private MyAuthenticationFailureHandler authenticationFailureHandler;

    //权限拒绝处理逻辑
    @Autowired
    private MyAccessDeniedHandler accessDeniedHandler;

    //匿名用户访问无权限资源时的异常
    @Autowired
    private MyAuthenticationEntryPoint authenticationEntryPoint;

    //会话失效(账号被挤下线)处理逻辑
    @Autowired
    private MySessionInformationExpiredStrategy sessionInformationExpiredStrategy;

    //登出成功处理逻辑
    @Autowired
    private MyLogoutSuccessHandler logoutSuccessHandler;

    //访问决策管理器
    @Autowired
    private MyAccessDecisionManager myAccessDecisionManager;

    //实现权限拦截
    @Autowired
    private MyFilterInvocationSecurityMetadataSource securityMetadataSource;

    //@Autowired
    //private MyFilterSecurityInterceptor securityInterceptor;

    //验证码过滤器
    //@Autowired
    private ImageCodeValidateFilter imageCodeValidateFilter = new ImageCodeValidateFilter();



    /**
     * @Description: 配置userDetails的数据源，密码加密格式
     **/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailService).passwordEncoder(new BCryptPasswordEncoder());
    }

    /**
     * @Description: 配置放行的资源
     **/
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/")
                .antMatchers("/index.html")
                .antMatchers("/codeImage")
                .antMatchers("/error")
                .antMatchers("**.html")
                .antMatchers("**.gif")
                .antMatchers("**.png")
                .antMatchers("**.jpg")
                .antMatchers("/js/**")
                .antMatchers("/css/**")
                .antMatchers("/images/**")
                //swagger
                .antMatchers("/swagger-ui.html")
                .antMatchers("/swagger-resources/**")
                .antMatchers("/images/**")
                .antMatchers("/webjars/**")
                .antMatchers("/v2/**")
                .antMatchers("/configuration/**")
                .antMatchers("/csrf/**")
                .antMatchers("/csrf")
        ;
    }



    /**
     * @Description: HttpSecurity包含了原数据（主要是url）
     * 通过withObjectPostProcessor将MyFilterInvocationSecurityMetadataSource和MyAccessDecisionManager注入进来
     * 此url先被MyFilterInvocationSecurityMetadataSource处理，然后 丢给 MyAccessDecisionManager处理
     * 如果不匹配，返回 MyAccessDeniedHandler
     **/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
        http.headers().frameOptions().disable();
        http.csrf().disable();

        http.authorizeRequests()
            //.antMatchers("/","/login","/codeImage").permitAll()
            .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                @Override
                public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                    o.setAccessDecisionManager(myAccessDecisionManager);//决策管理器
                    o.setSecurityMetadataSource(securityMetadataSource);//安全元数据源
                    return o;
                }
            })
            //登入
            .and().formLogin()//.loginPage("/index.html").loginProcessingUrl("/login")
            .permitAll()//允许所有用户
            .successHandler(authenticationSuccessHandler)//登录成功处理逻辑
            .failureHandler(authenticationFailureHandler)//登录失败处理逻辑
            //登出
            .and().logout()
            .permitAll()//允许所有用户
            .logoutSuccessHandler(logoutSuccessHandler)//登出成功处理逻辑
            .deleteCookies("JSESSIONID")//登出之后删除cookie
            //异常处理(权限拒绝、登录失效等)
            .and().exceptionHandling()
            .accessDeniedHandler(accessDeniedHandler)//权限拒绝处理逻辑
            .authenticationEntryPoint(authenticationEntryPoint)//匿名用户访问无权限资源时的异常处理
            //会话管理
            .and().sessionManagement()
            .maximumSessions(1)//同一账号同时登录最大用户数
            .expiredSessionStrategy(sessionInformationExpiredStrategy)//会话失效(账号被挤下线)处理逻辑
        ;

        //http.addFilterBefore(imageCodeValidateFilter, UsernamePasswordAuthenticationFilter.class);
        //http.addFilterBefore(securityInterceptor, FilterSecurityInterceptor.class);

    }



}
